package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private MenuDao menuDao;

    @Override
    public LinkedHashSet<Menu> getUsernameAndMenus(String username) {
        User user = userDao.findByUsername(username);
        if (user == null) {
            return null;
        }
        // 获取Role
        Integer userId = user.getId();
        Set<Role> roles = roleDao.findByUserId(userId);
        LinkedHashSet<Menu> parentMenus = new LinkedHashSet<>();
        if (roles != null && roles.size() > 0) {
            for (Role role : roles) {
                Integer roleId = role.getId();
                parentMenus = menuDao.getParentMenus(roleId);
                for (Menu parentMenu : parentMenus) {
                    Integer parentMenuId = parentMenu.getId();
                    List<Menu> childMenus = menuDao.getChildrenMenus(roleId, parentMenuId);
                    parentMenu.setChildren(childMenus);
                }
            }
        }
        return parentMenus;
    }


    public User findByUsername(String username) {

        // ��ȡUser
        User user = userDao.findByUsername(username);
        if (user == null) {
            return null;
        }

        // ��ȡRole
        Integer userId = user.getId();
        Set<Role> roles = roleDao.findByUserId(userId);

        // ��ȡPermission
        if (roles != null && roles.size() > 0) {
            for (Role role : roles) {
                Integer roleId = role.getId();
                Set<Permission> permissions = permissionDao.findByRoleId(roleId);
                if (permissions != null && permissions.size() > 0) {
                    role.setPermissions(permissions);
                }
            }
            user.setRoles(roles);
        }

        return user;
    }

    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) throws Exception {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage, pageSize);
        Page<Map<String,Object>> page = userDao.findPage(queryString);
        List<Map<String,Object>> maps = page.getResult();
        for (Map<String,Object> map : maps) {
            Date birthday = (Date) map.get("birthday");
            map.put("birthday",DateUtils.parseDate2String(birthday,"yyyy-MM-dd"));
        }
        return new PageResult(page.getTotal(), maps);
    }

    //添加用户
    @Override
    public void add(User user, Integer[] roleIds) {
        BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
        String password = bcryptPasswordEncoder.encode(user.getPassword());
        user.setPassword(password);
        userDao.addUser(user);

        Integer userId = user.getId();
        addUserRole(userId, roleIds);

    }

    //用户信息回显
    @Override
    public User findById(int id) {
        User user = userDao.findById(id);
        user.setPassword("");
        return user;
    }

    //添加用户角色关联信息
    public void addUserRole(int id, Integer[] roleIds) {
        if (roleIds != null && roleIds.length > 0) {
            for (Integer roleId : roleIds) {
                Map<String, Integer> roleIdMap = new HashMap<>();
                roleIdMap.put("userId", id);
                roleIdMap.put("roleId", roleId);
                userDao.addRole(roleIdMap);
            }
        }
    }

    //更新用户信息
    @Override
    public void update(Map<String, Object> map) throws Exception {
        BCryptPasswordEncoder bcryptPasswordEncoder = new BCryptPasswordEncoder();
        String password = bcryptPasswordEncoder.encode((String) map.get("password"));
        map.put("password", password);
        String date = (String) map.get("birthday");
        String birthday = parseDateZone(date);
        map.put("birthday", DateUtils.parseString2Date(birthday));
        userDao.update(map);
        Integer id = (Integer) map.get("id");
        userDao.deleteRoleByUserId(id);
        List<Integer> roleIdList = (List<Integer>) map.get("roleIds");
        Integer[] roleIds = new Integer[roleIdList.size()];
        addUserRole(id, roleIdList.toArray(roleIds));
    }

    //转换日期格式
    public String parseDateZone(String orderDate) {
        orderDate = orderDate.replace("Z", " UTC");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z");
        SimpleDateFormat defaultFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        String result = null;
        try {
            date = format.parse(orderDate);
            result = defaultFormat.format(date);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    //删除用户
    @Override
    public void delete(int id) {
        userDao.deleteRoleByUserId(id);
        userDao.delete(id);
    }
}